package br.com.cardapiolivre.persistencia;

import br.com.cardapiolivre.entidades.Entidade;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public abstract class DaoJpa<T extends Entidade> {

    static EntityManagerFactory emf = Persistence.createEntityManagerFactory("cardapiolivrePU");
    static EntityManager em = emf.createEntityManager();

    public T salvar(T obj) throws Exception {
        try {
            em.getTransaction().begin();
            if (obj.getId() == null) {
                em.persist(obj);
            } else {
                obj = em.merge(obj);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception("Erro ao salvar.");
        }
        return obj;
    }

    public void excluir(T obj) throws Exception {
        try {
            em.getTransaction().begin();
            em.remove(obj);
            em.getTransaction().commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception("Erro ao excluir.");
        }
    }

    public abstract T consultar(Long id) throws Exception;

    public abstract List<T> consultar() throws Exception;
}
